package br.com.dts.box
{
	import mx.utils.ObjectUtil;
	
	
	public class BOXEncode
	{
		private var _object:Object;
		
		public function BOXEncode(object:Object)
		{
			_object=object;
		}
		
		public function getXML():XML
		{
			var xml:XML=ObjectUtil.copy(BOXSchemas[_object["className"]]) as XML;
			
			setObject(xml, _object);
			
			return xml;
		}
		
		private function setObject(xml:XML, object:Object):void
		{
			// Preenche as propriedades com seus respectivos valores
			xml.properties.property.(setProperty(valueOf(), object));
			
			// Preenche os estilos com seus respectivos valores
			if ("getStyle" in object)
				xml.styles.style.(setStyle(valueOf(), object));
			
			// Cria os objetos filhos
			if (object["numChildren"] > 0)
				xml.children.(createObjects(valueOf(), object));
		}
		
		private function setProperty(node:XML, object:Object):void
		{
			if (!("@value" in node))
				node.@value=object[node.@name];
		}
		
		private function setStyle(node:XML, object:Object):void
		{
			if (!("@value" in node))
				node.@value=object["getStyle"](node.@name);
		}
		
		private function createObjects(node:XML, object:Object):void
		{
			var xmlChild:XML=ObjectUtil.copy(BOXSchemas[_object["className"]]) as XML;
			
			for (var i:uint=0; i < object["numChildren"]; i++)
			{
				var child:Object=object["getChildAt"](i);
				
				setObject(xmlChild, child);
			}
			
			node.appendChild(xmlChild);
		}

	}
}